<script setup lang="ts">
import { getSubjectListByUserId, getSubjectList, removeSubject } from '@/api/subject';
import { Subject } from '@/api/subject/type';
import { router } from '@/router';
import { onMounted, ref } from 'vue';
import { showToast, showDialog } from 'vant';
import { useUserStore } from '@/store/user';

const subjectList = ref([] as Subject[]);
const loading = ref(false);
const refreshing = ref(false);
const isManageMode = ref(false); // 管理模式状态

const toCreate = () => {
    router.push({name: 'SubjectCreate'});
}

const fetchSubjectList = async () => {
    try {
        loading.value = true;
        const userStore = useUserStore();
        const res = await getSubjectListByUserId(userStore.getId);
        // const res = await getSubjectList();
        subjectList.value = res.data;
    } catch (error) {
        showToast('获取题目集失败');
    } finally {
        loading.value = false;
        refreshing.value = false;
    }
};

onMounted(() => {
    fetchSubjectList();
});

const toHome = (id: string) => {
    // 管理模式下不跳转
    if (isManageMode.value) return;
    
    router.push({
        name: "SubjectHome",
        query: {
            "id": id
        }
    });
}

const onRefresh = () => {
    refreshing.value = true;
    fetchSubjectList();
}

const toggleManageMode = () => {
    isManageMode.value = !isManageMode.value;
}

const confirmDelete = (event: Event, id: string, name: string) => {
    // 阻止冒泡，避免触发toHome
    event.stopPropagation();
    
    showDialog({
        title: '删除题目集',
        message: `确定要删除"${name}"题目集吗？`,
        showCancelButton: true,
        confirmButtonText: '删除',
        confirmButtonColor: '#ee0a24',
    }).then(() => {
        deleteSubject(id);
    }).catch(() => {
        // 用户取消删除
    });
}

const deleteSubject = async (id: string) => {
    try {
        await removeSubject(id);
        showToast('删除成功');
        fetchSubjectList();
    } catch (error) {
        showToast('删除失败');
    }
}
</script>

<template>
  <div class="subject-list">
    <div class="subject-header">
      <div class="main-title">
        <h2>我的题目集</h2>
        <div class="count-badge" v-if="subjectList.length > 0">{{ subjectList.length }}</div>
      </div>
      <div class="header-actions">
        <button 
            class="action-button"
            :class="{ 'active': isManageMode }"
            @click="toggleManageMode"
        >
          <van-icon :name="isManageMode ? 'success' : 'setting-o'" />
          <span>{{ isManageMode ? '完成' : '管理' }}</span>
        </button>
        <button class="action-button primary" @click="toCreate">
          <van-icon name="plus" />
          <span>创建题目集</span>
        </button>
      </div>
    </div>
    
    <div class="subject-content">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh" success-text="刷新成功">
        <van-empty 
          v-if="!loading && subjectList.length === 0" 
          description="暂无题目集" 
          image="search"
        >
          <template #bottom>
            <van-button round type="primary" class="create-empty-btn" @click="toCreate">
              创建我的第一个题目集
            </van-button>
          </template>
        </van-empty>
        
        <div v-else class="subject-grid">
          <van-skeleton title avatar :row="3" :loading="loading" v-for="i in 6" :key="`skeleton-${i}`" v-if="loading"></van-skeleton>
          
          <div 
            v-for="(item, index) in subjectList" 
            :key="item.id" 
            class="subject-card"
            :class="{ 'manage-mode': isManageMode }"
            @click="toHome(item.id)"
          >
            <div class="card-content">
              <div class="subject-avatar">
                <van-image :src="item.avatar" width="100%" height="100%" radius="8px" fit="cover"></van-image>
              </div>
              <div class="subject-info">
                <h3 class="subject-name">{{ item.name }}</h3>
                <div class="subject-meta">
                  <span class="creator">{{ item.creator?.nickname || '未知创建者' }}</span>
                </div>
              </div>
            </div>
            
            <div v-if="isManageMode" class="delete-action" @click.stop="(e) => confirmDelete(e, item.id, item.name)">
              <van-icon name="delete-o" class="delete-icon" />
              <span>删除</span>
            </div>
          </div>
        </div>
      </van-pull-refresh>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.subject-list {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  
  .subject-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 24px;
    border-bottom: 1px solid #f0f2f5;
    
    .main-title {
      display: flex;
      align-items: center;
      
      h2 {
        font-size: 20px;
        font-weight: 600;
        color: #333;
        margin: 0;
      }
      
      .count-badge {
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f0f2f5;
        color: #666;
        font-size: 14px;
        height: 24px;
        min-width: 24px;
        padding: 0 8px;
        border-radius: 12px;
        margin-left: 12px;
      }
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
      
      .action-button {
        display: flex;
        align-items: center;
        gap: 6px;
        height: 36px;
        padding: 0 16px;
        border-radius: 18px;
        font-size: 14px;
        font-weight: 500;
        border: 1px solid #dcdfe6;
        background-color: #fff;
        color: #606266;
        cursor: pointer;
        transition: all 0.2s;
        
        &:hover {
          background-color: #f5f7fa;
        }
        
        &.active {
          background-color: #ecf5ff;
          color: #409eff;
          border-color: #d9ecff;
        }
        
        &.primary {
          background-color: #409eff;
          border-color: #409eff;
          color: white;
          
          &:hover {
            background-color: #66b1ff;
            border-color: #66b1ff;
          }
        }
      }
    }
  }
  
  .subject-content {
    padding: 20px;
    min-height: 300px;
  }
  
  .subject-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 20px;
    
    .subject-card {
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
      overflow: hidden;
      transition: all 0.2s;
      border: 1px solid #ebeef5;
      position: relative;
      cursor: pointer;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
      }
      
      &.manage-mode {
        background-color: #fafafa;
        
        .delete-action {
          display: flex;
        }
      }
      
      .card-content {
        padding: 16px;
      }
      
      .subject-avatar {
        width: 100%;
        height: 140px;
        margin-bottom: 12px;
        background-color: #f5f7fa;
        border-radius: 8px;
        overflow: hidden;
      }
      
      .subject-info {
        .subject-name {
          font-size: 16px;
          font-weight: 500;
          margin: 0 0 8px 0;
          color: #303133;
          line-height: 1.4;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        
        .subject-meta {
          display: flex;
          align-items: center;
          color: #909399;
          font-size: 13px;
          
          .creator {
            display: block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
      
      .delete-action {
        display: none;
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        padding: 10px 0;
        background-color: rgba(245, 108, 108, 0.9);
        color: white;
        align-items: center;
        justify-content: center;
        gap: 6px;
        font-size: 14px;
        
        &:hover {
          background-color: rgba(245, 108, 108, 1);
        }
      }
    }
  }
}

.create-empty-btn {
  padding: 0 20px;
  height: 40px;
}

// 响应式调整
@media (max-width: 768px) {
  .subject-header {
    flex-direction: column;
    align-items: flex-start;
    
    .header-actions {
      margin-top: 16px;
      width: 100%;
      
      .action-button {
        flex: 1;
        justify-content: center;
      }
    }
  }
  
  .subject-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;
  }
}
</style>